import 'package:flutter_dva/flutter_dva.dart';
import 'package:todo_app/components/Overlay/main.dart';
import 'package:todo_app/controllers/UserController.dart';
import 'package:todo_app/controllers/definitions/UserModel.dart';
import 'package:todo_app/utils/ApiService.dart';
import 'package:todo_app/utils/AppNavigator.dart';
import 'package:todo_app/utils/OAuthController.dart';
import 'package:todo_app/utils/SharedPreferencesUtil.dart';

class SystemModel implements Model<SystemState> {
  @override
  Map<String, EffectFunction> effects = <String, EffectFunction>{
    login:(action, effects) async {
      var user = action.payload as UserModel;
      var currentState = effects.getCurrentState() as SystemState;
      var loading = showOverlayLoading(title: "正在登录");
      currentState.loginSuccess = false;
      try {
        var data = await  OAuthController.passwordToken(user.username!, user.password!);
        if(data.accessToken != null) {
          SharedPreferenceUtil.setString(ApiService.ACCESS_TOKEN, data.accessToken!);
          // 如果是首次登录 则需要降首次执行登录重置为false
          if(currentState.isFirstLogin == true) {
            currentState.isFirstLogin = false;
          }
          // 登录成功
          currentState.loginSuccess = true;
          // 进入首页
          AppNavigator.goNamed('home');

          // 更新完state，需要保存下数据
          effects.dispatch(DvaAction("save", currentState));
          // 获取用户信息
          effects.dispatch(DvaAction("getUserInfo", currentState));
        }
      } catch (e) {
        print(e);
      } finally {
        loading.remove();
      }
    },
    register: (action, effects) async {
      var user = action.payload as UserModel;
      var currentState = effects.getCurrentState() as SystemState;
      var loading = showOverlayLoading(title: "正在登录");
      currentState.loginSuccess = false;
      try {
        var data = await UserController.registerUsingPost(user);
        if(data.status == 'sucess') {
          showOverlayToast("注册成功");
          // 退回登录界面
          AppNavigator.goNamed('login');
        }
      } catch (e) {
        print(e);
      } finally {
        loading.remove();
      }
    },
    logout: (action, effects) async {
      var currentState = effects.getCurrentState() as SystemState;
      // 登录是否成功
      currentState.loginSuccess = false;
      // 更新完state，需要保存下数据
      effects.dispatch(DvaAction("save", currentState));
      // 退出到登录界面
      AppNavigator.goNamed('login');
    },
    getUserInfo: (action, effects) async {
      var currentState = effects.getCurrentState() as SystemState;
      var loading = showOverlayLoading(title: "正在获取用户信息");
      try {
        var res = await  UserController.currentUsingGet();
        if(res.status == 'success' && res.data is UserModel) {
          var user = res.data as UserModel;
          currentState.user = user;
          // 更新完state，需要保存下数据
          effects.dispatch(DvaAction("save", currentState));
        } else {
          showOverlayToast(res.msg ?? "获取用户信息失败");
        }
      } catch (e) {
        print(e);
      } finally {
        loading.remove();
      }
    },
  };

  @override
  String namespace = "system";

  @override
  Map<String, ReducerFuction> reducers = <String, ReducerFuction>{
    'save': (StoreOfState<dynamic> lastState, DvaAction action) {
      lastState.setState(action.payload);
      return lastState;
    }
  };

  @override
  StoreOfState<SystemState> state = StoreOfState<SystemState>(state: SystemState());
  /// 发送短信
  static String login = "login";
  /// 退出
  static String logout = "logout";
  /// 获取用户信息
  static String getUserInfo = "getUserInfo";
  /// 注册
  static String register = 'register';
}

class SystemState extends DvaState {
  SystemState({
    user,
    isFirstLogin
  });
  /// 用户信息
  UserModel? user;
  /// 是否是第一次登录
  bool? isFirstLogin;
  /// 是否发送成功
  bool? sendSuccess;
  /// 登录是否成功
  bool? loginSuccess;
  // 登录过后返回
  OAuthResponse? oauthRes;

  @override
  void fromJson(Map<String,dynamic> json) {
    user = UserModel()..fromJson(json['user']);
    isFirstLogin = json['isFirstLogin'] ?? true;
    loginSuccess = json['loginSuccess'] ?? false;
    sendSuccess = json['sendSuccess'] ?? false;
    oauthRes = OAuthResponse()..fromJson(json['oauthRes']);
  }

  @override
  Map<String,dynamic> toJson() =><String,dynamic>{
    'user': user?.toJson(),
    "isFirstLogin": isFirstLogin,
    "loginSuccess": loginSuccess,
    "sendSuccess": sendSuccess,
    "oauthRes": oauthRes?.toJson(),
  };
}